import re
from selenium import webdriver
import time

"""
version 2020-7-2 09:46:10
version 2020-7-13 09:39:28
"""


##########################################New Browser Visitor##################################################
class NBVisitor:
    Module_Name = "M_WEIBO_CN"
    CSS_Of_Reply = ".m-img-box+div"
    CSS_Of_User_Name = ".m-text-box>a>h3.m-text-cut"
    CSS_Of_Text = ".weibo-og>.weibo-text"
    CSS_Of_Time = "h4.m-text-cut>.time"
    CSS_Fabulous = ""
    d = None

    def __init__(
            self,
            Name: str,
            CSS_Reply: str,
            CSS_User: str,
            CSS_Text: str,
            CSS_Time: str,
            CSS_Fabulous: str,
            BrowserDriver: webdriver.Chrome
    ):
        self.Module_Name = Name
        self.CSS_Of_Time = CSS_Time
        self.CSS_Of_Text = CSS_Text
        self.CSS_Of_User_Name = CSS_User
        self.CSS_Of_Reply = CSS_Reply
        self.CSS_Fabulous = CSS_Fabulous
        self.d = BrowserDriver

    def go(self, link: str, delay=2):
        if delay != 2:
            print("现在，延迟已被修改为：%d" % delay)
        r = self.go_for_a_weibo(link, delay=delay)
        if len(r) == 0:
            time.sleep(delay + 1)
            r = self.go_for_a_weibo(link, delay=delay)
        return r

    def sim_forment_time_str(self, time_str: str):
        l = time_str.split('-')
        return "%04d-%02d-%02d" % (int(l[0]), int(l[1]), int(l[2]))

    def chick_dictionary(self, a_weibo: dict):
        min_time_str = self.sim_forment_time_str(a_weibo['date'])
        min_time = int(min_time_str.replace('-', ''))
        for reply in a_weibo['reply']:
            reply_time_str = self.sim_forment_time_str(reply['date'])
            reply_time = int(min_time_str.replace('-', ''))
            if reply_time < min_time:
                min_time = reply_time
                min_time_str = reply_time_str
        a_weibo['date'] = min_time_str
        return a_weibo

    def build_a_weibo(self, username: str, date: str, text: str, fabulous="0", reply_num=0, reply=None, link=""):
        if reply is None:
            reply = []
        return {
            "username": username,
            "date": date,
            "text": text,
            "fabulous": fabulous,
            "link": link,
            "reply_num": reply_num,
            "reply": reply
        }

    def full_time(self, time_str):
        # 获取当前时间，如果没有，则为当前时间
        t = time.localtime(time.time())
        now = "%4d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)  # 现在的时间
        # 正则表达式匹配日期值
        cmp = re.compile(r"\d{4}-\d{1,2}-\d{1,2}")  # 2019-06-28
        res = cmp.match(time_str)
        if res is not None:
            return res.group()
        else:
            cmp = re.compile(r"\d{1,2}-\d{1,2}")  # 06-28
            res = cmp.match(time_str)
            if res is not None:
                return "%4d-%s" % (t.tm_year, str(res.group()))
            elif time_str.find("天前") >= 0 and time_str.find(". ") >= 0:
                word = time_str.split("·")[1].split("天")[0]
                t = time.localtime(time.time() - int(word) * 24 * 60 * 60)
                return "%4d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
            elif time_str.find("月") >= 0 and time_str.find("日") >= 0:
                cmp = re.compile(r"\d{1,2}月\d{1,2}日")  # 06月28日
                res = cmp.match(time_str)
                if res is not None:
                    return "%4d-%s" % (t.tm_year, str(res.group()).replace('月', '-').replace('日', ''))
                else:
                    return now
            else:
                return now

    def get_all_div_of_weiboCN_reply(self):
        while True:
            set_A = self.d.find_elements_by_css_selector(self.CSS_Of_Reply)
            self.d.execute_script("window.scrollBy(0,100000)")
            print("1..", end='')
            time.sleep(0.5)
            self.d.execute_script("window.scrollBy(0,100000)")
            print("2..", end='')
            time.sleep(0.5)
            self.d.execute_script("window.scrollBy(0,100000)")
            print("3..", end='')
            time.sleep(0.5)

            set_B = self.d.find_elements_by_css_selector(self.CSS_Of_Reply)

            print(str(len(set_A)) + ":" + str(len(set_B)))
            if (len(set_A) == len(set_B)):
                print(self.Module_Name + "> 满了！")
                time.sleep(1)
                if (len(set_A) == len(set_B)):
                    print(self.Module_Name + "> 真的满了！")
                    return set_B
                else:
                    print(self.Module_Name + "> 嘿嘿，我骗你的！")
            else:
                print(self.Module_Name + "> 还能滚动！")
                continue

    def reply_processor(self, reply_text):
        print(self.Module_Name + "> reply_processer: 此方法必须被重写。")
        raise Exception

    """
    def reply_processor(self, reply_text):
        ss = str(reply_text).split('\n')
        name = ss[0]
        text = ss[1]
        mydate = ss[-2]  # 倒数第二个
        mydate = self.full_time(mydate)
        praise = ss[-1]  # 点赞数，还没用
        return (self.build_a_weibo(
            username=name,
            text=text,
            date=mydate
        ))
    """

    def fabulous_processor(self, text: str):
        print(self.Module_Name + "> fabulous_processor: 此方法必须被重写。")
        raise Exception

    def go_for_a_weibo(self, link: str, delay=2):
        b_user = ""
        b_text = ""
        b_mytime = ""
        reply_list = []
        b_fabulous = 0
        good = 0  # 主页面都说到关键元素的数量
        time.sleep(0.5)
        self.d.get(link)
        time.sleep(delay)
        # 改动：先滚动获取回复！
        # 获取回复列表
        print("现在先滚...")
        reply_list = []
        set_div = self.get_all_div_of_weiboCN_reply()
        for a_div in set_div:
            rset = self.reply_processor(a_div.text)
            if len(rset) >= 1:
                reply_list.append(rset)
            else:
                continue

        b_res = self.d.find_elements_by_css_selector(self.CSS_Of_User_Name)
        if len(b_res) == 1:
            b_user = str(b_res[0].text)
            good += 1
        else:
            print("error in " + self.Module_Name + " username not found.")
            b_user = ""
            # return {}
        b_res = self.d.find_elements_by_css_selector(self.CSS_Of_Text)
        if len(b_res) == 1:
            b_text = str(b_res[0].text)
            good += 1
        else:
            print("error in " + self.Module_Name + " text not found.")
            b_text = ""
            # return {}
        b_res = self.d.find_elements_by_css_selector(self.CSS_Of_Time)
        if len(b_res) == 1:
            b_mytime = self.full_time(str(b_res[0].text))
            good += 1
        else:
            print("error in " + self.Module_Name + " timebox not found.")
            b_mytime = ""
            # return {}
        b_res = self.d.find_elements_by_css_selector(self.CSS_Fabulous)
        if len(b_res) == 1:
            b_fabulous = self.fabulous_processor(str(b_res[0].text))
        else:
            print("warning in " + self.Module_Name + " fabulous not found.")
            b_fabulous = "0"
        print("good = %d, " % good, end='')
        if (good >= 2):
            print("符合最低要求.")
        else:
            print("不符合最低要求.")
            return {}
        """# 获取回复列表
        reply_list = []
        set_div = self.get_all_div_of_weiboCN_reply()
        for a_div in set_div:
            reply_list.append(self.reply_processor(a_div.text))"""
        return self.chick_dictionary(
            self.build_a_weibo(
                username=b_user,
                date=self.full_time(b_mytime),
                text=b_text,
                reply_num=len(reply_list),
                fabulous=b_fabulous,
                reply=reply_list,
                link=str(self.d.current_url)
            )
        )


"""
########例子：我的新类#########
class Test_WeiBoCOM_Visitor(NBVisitor):
    def reply_processor(self, reply_text:str):#重写父方法
        b_s = str(reply_text).split('\n')
        s_s = b_s[0].split(':')
        name = s_s[0]
        text = s_s[1]
        mydate = b_s[1]  # 倒数第二个
        mydate = self.full_time(mydate)
        praise = b_s[2]  # 点赞数，还没用
        return (build_a_weibo(
            username=name,
            text=text,
            date=mydate
        ))


#########################
AAA = NBVisitor(
    Name="WEIBOCN",
    CSS_Reply=".m-img-box+div",
    CSS_User=".m-text-box>a>h3.m-text-cut",
    CSS_Text=".weibo-og>.weibo-text",
    CSS_Time="h4.m-text-cut>.time",
    BrowserDriver=dd
)
#a = AAA.go_for_a_weibo("https://m.weibo.cn/status/4518319245724839")

BBB = Test_WeiBoCOM_Visitor(
    Name="测试一号",
    CSS_Text=".woo-box-item-flex.Txt_cut_1Pb86",
    CSS_User="div.star-autocut.star-f16",
    CSS_Reply=".vue-recycle-scroller__item-view",
    CSS_Time=".woo-box-flex.woo-box-alignCenter.woo-box-justifyBetween.Detail_tith4_3_UzS .star-f16",
    BrowserDriver=dd
)
#a = go_for_a_weiboCOM("https://m.weibo.cn/status/4518319245724839")
#a = BBB.go_for_a_weibo("https://weibo.com/tv/show/2017607:4520211899154472")

#print(a)
############################################################################################"""
